import React,{ useEffect, useState } from 'react'
import { withRouter } from 'react-router-dom';
import { Card,Select,Input,Button,Space, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import MyTable from './components/Table'
import { reqProductList,reqProductUpdateStatus } from '../../api';
import './Product.css'

const { Option } = Select
/* 
  商品管理路由
*/
export default withRouter( function Product(props) {

  const [searchText, setSearchText] = useState('');
  const [searchType, setSearchType] = useState('s_1');
  const [list, setList] = useState([]);
  const [searchList, setSearchList] = useState([]);

  const changeSearchType=(type)=>{
    setSearchType(type)
  }
  const searchGoods=()=>{
    if(searchType==='s_1'){
      setSearchList(list.filter(i=>i.name.includes(searchText)))
    }else{
      setSearchList(list.filter(i=>i.desc.includes(searchText)))
    }
  }
  const searchTextChange=(s)=>{
    setSearchText(s.target.value)
  }
  const changeStatus=(item)=>{
    reqProductUpdateStatus({_id:item._id}).then(res=>{
      message.success(res.msg)
      setList([])
    }).catch(err=>{
      message.error(err)
    })
  }
  const modifyGoods=(item)=>{
    item.type='modify'
    props.history.push('/product/addAndModify',item,)
  }

  useEffect(()=>{
    async function getList(){
      let res=await reqProductList()
      setList(res.data)
    }
    if(list.length===0)getList()
    if(searchText==='')setSearchList([])
  },[list,searchText])

  const title=(
    <>
      <Space>
        <Select defaultValue="s_1" style={{ width: 120 }} onChange={changeSearchType}>
          <Option value="s_1">按名称搜索</Option>
          <Option value="s_2">按描述搜索</Option>
        </Select>
        <Input bordered placeholder='关键字' onChange={searchTextChange} allowClear={true}/>
        <Button type='primary' onClick={searchGoods}>搜索</Button>
      </Space>
    </>
  )

  return (
    <div className='product'>
      <Card title={title} extra={<Button type='primary' onClick={()=>props.history.push('/product/addAndModify',{type:'add'})}><PlusOutlined/>添加商品</Button>} style={{ width:'100%',height:'100%' }}>
        <MyTable {...{list,searchList,changeStatus,modifyGoods,...props}}></MyTable>
      </Card>
    </div>
  )
})
